#!/bin/bash
#批量ping域名

# 域名列表文件
DOMAINS_FILE="domains.txt"
# 结果保存文件
HOSTS_FILE="hosts.txt"

# 清空hosts文件，避免重复写入
> "$HOSTS_FILE"

# 定义解析IP地址的函数，支持IPv4和IPv6
parse_ip() {
    local ping_output="$1"
    # 提取IPv4
    local ipv4=$(echo "$ping_output" | grep -oE '([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})' | head -n1)
    # 提取IPv6
    local ipv6=$(echo "$ping_output" | grep -oE '((([a-fA-F0-9]{1,4}:){1,7}[a-fA-F0-9]{1,4})' | head -n1)
    if [ -n "$ipv4" ]; then
        echo "$ipv4"
    elif [ -n "$ipv6" ]; then
        echo "$ipv6"
    fi
}

# 读取域名列表并ping每个域名
while IFS='' read -r domain; do
    # 使用ping命令，并尝试解析IP地址
    ping_output=$(ping -c 1 "$domain" 2>&1)
    ip=$(parse_ip "$ping_output")
    if [ -n "$ip" ]; then
        echo "$domain $ip" >> "$HOSTS_FILE"
        echo "Domain: $domain, IP: $ip"
    else
        echo "Failed to ping or resolve IP for $domain"
    fi
done < "$DOMAINS_FILE"

echo "Done. Results saved in $HOSTS_FILE"
